﻿using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System;
using System.Collections.Generic;
using System.Threading;

namespace ServiceBus
{
    //
    //https://msdn.microsoft.com/en-us/library/jj193022(v=azure.10).aspx
    //http://stackoverflow.com/questions/15398665/microsoft-service-bus-on-a-windows-workgroup
    //http://stackoverflow.com/questions/12462894/connecting-to-windows-server-service-bus-on-aws
//get-SBClientconfiguration
    internal class Program
    {
        private static QueueClient queueClient;
        private static string QueueName = "JymTestSbDemo";

        private static void CreateQueue()
        {
            ////string ServerFQDN = "JYM-Win2012R2-S.ad.jinyinmao.com.cn";
            ////int HttpPort = 9355;
            ////int TcpPort = 9354;
            ////string ServiceNamespace = "SbDemo";

            //ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder();
            ////connBuilder.ManagementPort = HttpPort;
            ////connBuilder.RuntimePort = TcpPort;
            ////connBuilder.Endpoints.Add(new UriBuilder() { Scheme = "sb", Host = ServerFQDN, Path = ServiceNamespace }.Uri);
            ////connBuilder.StsEndpoints.Add(new UriBuilder() { Scheme = "https", Host = ServerFQDN, Port = HttpPort, Path = ServiceNamespace }.Uri);

            //NamespaceManager nm = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());
            ////TokenProvider localUserTokenProvider = WindowsTokenProvider.CreateWindowsTokenProvider(
            ////    connBuilder.StsEndpoints,
            ////    new System.Net.NetworkCredential("zhao.gaolei@jinyinmao.com.cn", "Zhao19881226"));

            //MessagingFactory factory = MessagingFactory.Create(
            //            connBuilder.GetAbsoluteRuntimeEndpoints(), localUserTokenProvider);
            //NamespaceManager nm = new NamespaceManager(
            //            connBuilder.GetAbsoluteManagementEndpoints(), localUserTokenProvider);

            //if (nm.QueueExists(QueueName))
            //{
            //    nm.DeleteQueue(QueueName);
            //}
            //nm.CreateQueue(QueueName);
            // Console.WriteLine("Create Queue successful!");

            NamespaceManager nm = NamespaceManager.Create();
            if (nm.QueueExists(QueueName))
            {
                nm.DeleteQueue(QueueName);
            }
            nm.CreateQueue(QueueName);
            Console.WriteLine("Create Queue successful!");
        }

        private static void Main(string[] args)
        {
            ////MessagingFactory messagingFactory = MessagingFactory.Create();
            ////NamespaceManager namespaceManager = NamespaceManager.Create();

            //ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder();
            //connBuilder.ManagementPort = HttpPort;
            //connBuilder.RuntimePort = TcpPort;
            //connBuilder.Endpoints.Add(new UriBuilder() { Scheme = "sb", Host = ServerFQDN, Path = ServiceNamespace }.Uri);
            //connBuilder.StsEndpoints.Add(new UriBuilder() { Scheme = "https", Host = ServerFQDN, Port = HttpPort, Path = ServiceNamespace }.Uri);

            //MessagingFactory messagingFactory = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
            //NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

            try
            {
                Console.WriteLine("Create Queue");
                CreateQueue();
                Console.ReadKey();
                Console.WriteLine("Send Message");
                SendMessage();
                Console.ReadKey();
                Console.WriteLine("Receive Message");
                ReceiveMessage();
                0}
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

        private static void ReceiveMessage()
        {
            BrokeredMessage m = null;
            while (true)
            {
                try
                {
                    m = queueClient.Receive(TimeSpan.FromSeconds(5));
                    if (m != null)
                    {
                        Console.WriteLine("message id={0}, content={1}", m.MessageId, m.GetBody<string>());
                        m.Complete();
                    }
                    else
                    {
                        break;
                    }
                }
                catch
                {
                }
            }
        }

        private static void SendMessage()
        {
            BrokeredMessage m1 = new BrokeredMessage("hello queue 1!");
            m1.MessageId = "1";
            BrokeredMessage m2 = new BrokeredMessage("hello queue 2!");
            m2.MessageId = "2";
            BrokeredMessage m3 = new BrokeredMessage("hello queue 3!");
            m3.MessageId = "3";
            BrokeredMessage m4 = new BrokeredMessage("hello queue 4!");
            m4.MessageId = "4";
            BrokeredMessage m5 = new BrokeredMessage("hello queue 5!");
            m5.MessageId = "5";

            queueClient = QueueClient.Create(QueueName);
            List<BrokeredMessage> msgList = new List<BrokeredMessage>();
            msgList.Add(m1);
            msgList.Add(m2);
            msgList.Add(m3);
            msgList.Add(m4);
            msgList.Add(m5);

            foreach (var item in msgList)
            {
                try
                {
                    queueClient.Send(item);
                }
                catch (MessagingException ex)
                {
                    if (ex.IsTransient)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine("please wait 2 second");
                        Thread.Sleep(2000);
                    }
                    else
                    {
                        throw;
                    }
                }
                Console.WriteLine("message {0} was sent successfully", item.MessageId);
            }
        }
    }
}

//using Microsoft.ServiceBus;
//using Microsoft.ServiceBus.Messaging;
//using System;
//using System.Net;
//using System.Net.Security;
//using System.Security.Cryptography.X509Certificates;

//namespace Test_Service_Bus
//{
//    public static class Util
//    {
//        public static void SetCertificatePolicy()
//        {
//            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
//        }

//        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
//        {
//            System.Console.WriteLine("Warning, trust any certificate");
//            return true;
//        }
//    }

//    internal class Program
//    {
//        //System.Net.Dns.GetHostEntry(string.Empty).HostName;
//        private static string ServerFQDN = "JYM-Win2012R2-S.ad.jinyinmao.com.cn";

//        private static int HttpPort = 9355;

//        private static int TcpPort = 9354;
//        private static string ServiceNameSpace = "ServiceBusDefaultNamespace";
//        private const string QueueName = "ServiceBusQueueSample";

//        private static void Main(string[] args)
//        {
//            SDKVersion();
//        }

//        private static void SDKVersion()
//        {
//            ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder();
//            connBuilder.ManagementPort = HttpPort;
//            connBuilder.RuntimePort = TcpPort;

//            connBuilder.Endpoints.Add(new UriBuilder() { Scheme = "sb", Host = ServerFQDN, Path = ServiceNameSpace }.Uri);
//            connBuilder.StsEndpoints.Add(new UriBuilder() { Scheme = "https", Host = ServerFQDN, Port = HttpPort, Path = ServiceNameSpace }.Uri);

//            TokenProvider localUserTokenProvider = WindowsTokenProvider.CreateWindowsTokenProvider(connBuilder.StsEndpoints, new System.Net.NetworkCredential("ServerLocalAcct", "ServerLocalPassword"));

//            MessagingFactory messageFactory = MessagingFactory.Create(connBuilder.GetAbsoluteRuntimeEndpoints(), localUserTokenProvider);
//            NamespaceManager namespaceManager = new NamespaceManager(connBuilder.GetAbsoluteManagementEndpoints(), localUserTokenProvider);

//            NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

//            if (namespaceManager == null)
//            {
//                Console.WriteLine("\nUnexpected error: NamespaceManager is NULL");
//                return;
//            }

//            Console.WriteLine("Checking if queue exists");
//            if (namespaceManager.QueueExists(QueueName))
//            {
//                Console.WriteLine("Queue exists, let's delete it so we can start over again");
//                namespaceManager.DeleteQueue(QueueName);
//            }

//            Console.WriteLine("And create a new queue");
//            namespaceManager.CreateQueue(QueueName);

//            // create a message client
//            QueueClient myQueueClient = messageFactory.CreateQueueClient(QueueName);

//            Console.WriteLine("Feeding messages");
//            for (int i = 0; i < 1000; i++)
//            {
//                if (i % 100 == 0)
//                    Console.WriteLine("Messages sent: {0}", i.ToString());

//                // send to message broker
//                using (BrokeredMessage sendMessage = new BrokeredMessage("Hello world. " + i.ToString()))
//                {
//                    sendMessage.Label = "Label_" + i.ToString(); ;
//                    myQueueClient.Send(sendMessage);
//                }
//            }

//            BrokeredMessage receivedMessage = myQueueClient.Receive(TimeSpan.FromSeconds(5));

//            while (receivedMessage != null)
//            {
//                Console.WriteLine(string.Format("Message Received: Body={0}", receivedMessage.GetBody<string>()));
//                receivedMessage.Complete();

//                receivedMessage = myQueueClient.Receive(TimeSpan.FromSeconds(5));
//            }

//            // Close things down.
//            Console.WriteLine("Closing down message");
//            if (messageFactory != null)
//            {
//                messageFactory.Close();
//            }
//        }
//    }
//}